package com.xiao.blogs.fragment;

import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.example.bokeyuan.R;
import com.xiao.activity.MainActivity;
import com.xiao.blogs.fragment.FragmentBlogsComment.DownloadNewsComment;
import com.xiao.bokeyuan.utils.HttpUtils;
import com.xiao.bokeyuan.utils.HttpUtils.Method;
import com.xiao.bokeyuan.utils.I;
import com.xiao.news.listview.NewsAdapter;
import com.xiao.news.listview.NewsInfo;
import com.xiao.slipUtils.D;
import com.xiao.slipUtils.SlideMenuUtils;

public class FragmentBlogs extends Fragment {
	FragmentTransaction mft;
	FragmentManager manager;
	ProgressDialog mpb;
	// 练习上下文
	MainActivity mContext;
	ListView mlistview;
	ArrayList<NewsInfo> mListNews;
	NewsAdapter mAdapter;
	NewsInfo mInfo;
	// 创建工具类对象返回touch事件
	SlideMenuUtils mSlideUtil;
	// listview单击事件
	OnItemClickListener itemClick;
	String uri;
	int startX;
	int startY;
	//用于监听向右滑时次数
		int i=0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = (MainActivity) getActivity();
		i=0;
		//		mContext.mFragmentHotNews = this;

		// mContext.mSlideTouch.hideLeftMenuListener();
		// 初始化listview
		View layout = inflater.inflate(R.layout.fragment_news_listview, null);
		initView(layout);
		setAdapter();
		//		if (mAdapter==null) {
		Bundle bundle = getArguments();
		String url = bundle.getString(D.NEWS_URL);
		uri=url;
		pullParserNews(url);
		//	}else{
		//		mAdapter.setData(mListNews);
		//	}
		setListViewListener();
		return layout;
	}

	/**
	 * listview按钮事件
	 */
	private void setListViewListener() {
		// TODO Auto-generated method stub

		//设置listview touch事件
		setOnListViewOnTouchEvent();
		// 设置lisetview 单个点击事件
		listViewItemClick();


	}

	private void listViewItemClick() {
		mlistview.setOnItemClickListener(new OnItemClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				// 获取所点击项的新闻ID
				String Id = mListNews.get(position).getId();
				// 获取点击项新闻内容的URL
				String url = I.URL_BLOG_CONTENT + Id;
				// 启动线程来下载新闻内容
				// Toast.makeText(mContext, "" + position, 2000).show();
				manager = getFragmentManager();
				mft = manager.beginTransaction();
				// 创建fragment对象
				Fragment fragment = new FragmentBlogsContent();
				Bundle b = new Bundle();
				b.putString(D.NEWS_URL, url);
				// 将对应的id也传给新闻内容fragment
				b.putString("id", Id);
				// 传递网址
				b.putString("link", mListNews.get(position).getLink());
				b.putString("title", mListNews.get(position).getTitle());
				fragment.setArguments(b);
				mft.setCustomAnimations(R.animator.left_in,R.animator.right_out);
				mft.replace(R.id.fl_details, fragment);

				mft.addToBackStack(null);
				mft.commit();
			}
		});
	}

	/**
	 * 设置listview touch事件
	 */
	private void setOnListViewOnTouchEvent() {
		mlistview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int upx=0;
				int moveX=0;
				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:
					startX=(int) event.getRawX();
					startY=(int) event.getRawY();
					mContext.QQutils.onTouch(v, event);
					break;

				case MotionEvent.ACTION_MOVE:
					moveX=(int) event.getRawX();
					int subx=startX-moveX;
					//					mlistview.sett
					//当listview菜单被滑动距离超过20时   才返回回调touch事件
					int x=Math.abs(subx);
					int y=(int) Math.abs((startY-event.getRawY()));
					if(subx<0&&x>y){
						//当移动的时候使listview失去触摸事件
						MotionEvent cancelEvent = MotionEvent.obtain(event);
						cancelEvent
						.setAction(MotionEvent.ACTION_CANCEL
								| (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
						v.onTouchEvent(cancelEvent);
						return mContext.QQutils.onTouch(v, event);
					}
					if(subx>0&&x>y){
						MotionEvent cancelEvent = MotionEvent.obtain(event);
						cancelEvent
						.setAction(MotionEvent.ACTION_CANCEL
								| (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
						v.onTouchEvent(cancelEvent);
						if(i==0){

							mContext.QQutils.hideLeftAndCenterMenu(0);
							i++;
						}

					}

					break;
				case MotionEvent.ACTION_UP:
					// TODO Auto-generated method stub
                     i=0;
					upx=(int) event.getRawX();
					if(upx>startX){
						mContext.QQutils.onTouch(v, event);
					}
					//得到Y抬起的值
					int upy=(int) event.getRawY();
					//判断最后一个可见的listview的位置
					int position = mlistview.getFirstVisiblePosition();
					//得到数组的长度
					//					int size=mListNews.size()-1;
					if(position==0&&(upy-startY)>50){
						pullParserNews(uri);
					}
					break;
				}



				return false;
			}
		});
	}
	/**
	 * touch的View是否是AbsListView， 例如ListView, GridView等其子类
	 * 
	 * @return
	 */
	private boolean isTouchOnAbsListView() {
		//		AbsListView touchView;
		return mlistview instanceof android.widget.AbsListView ? true : false;
	}

	private void setAdapter() {
		// TODO Auto-generated method stub
		mAdapter = new NewsAdapter(mListNews, mContext);

		mlistview.setAdapter(mAdapter);
	}

	// CommentAdapter NewsAdapter
	/**
	 * @param url
	 */
	private void pullParserNews(String url) {

		// if(url.equals(I.URL_HOST_NEWS)){
		new DownLoadNews().execute(url);

		// }
	}

	/**
	 * 初始化listview
	 */
	private void initView(View layout) {
		// TODO Auto-generated method stub
		mlistview = (ListView) layout.findViewById(R.id.listview_news);
		mListNews = new ArrayList<NewsInfo>();
	}

	/**
	 * 下载新闻线程类
	 * 
	 * @author 张效伟
	 * 
	 */
	class DownLoadNews extends AsyncTask<String, Void, ArrayList<NewsInfo>> {
		@Override
		protected void onPreExecute() {
			if(mpb==null){
				mpb=ProgressDialog.show(mContext, "数据加载中", "loding...");
				//					mpb=new ProgressDialog(mContext);
				//					mpb.setTitle("加载数据中");
				//					mpb.show();
			}else{
				mpb.show();
			}
		}
		@Override
		protected ArrayList<NewsInfo> doInBackground(String... params) {
			// TODO Auto-generated method stub
			String url = params[0];
			InputStream in;
			try {
				in = HttpUtils.getInputStream(url, null, Method.GET, "utf-8");
				// 创建pull工厂解析对象
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				// 创建解析器对象
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(in, "utf-8");
				for (int eventType = XmlPullParser.START_DOCUMENT; eventType != XmlPullParser.END_DOCUMENT; eventType = parser
						.next()) {
					if (eventType == XmlPullParser.START_TAG) {
						// 获取标签名称
						String tagName = parser.getName();
						if (D.Blogs.ENTITY.equals(tagName)) {
							mInfo = new NewsInfo();
						} else if (D.Blogs.ID.equals(tagName)) {
							// parser.nextText()获取标签的数据
							if (mInfo != null) {
								mInfo.setId(parser.nextText());

							} else {

							}

						} else if (D.Blogs.TITLE.equals(tagName)) {
							if (mInfo != null) {
								mInfo.setTitle(parser.nextText());
							}

						} else if (D.Blogs.SUMMARY.equals(tagName)) {
							mInfo.setContent(parser.nextText());
						} else if ("updated".equals(tagName)) {
							if (mInfo != null) {

								mInfo.setTime(parser.nextText());
							}
						} else if (D.Blogs.VIEWS.equals(tagName)) {
							mInfo.setBrowse(parser.nextText());
						} else if (D.Blogs.LINK.equals(tagName)) {
							if (mInfo != null) {
								mInfo.setLink(parser.getAttributeValue(1));
							}
						} else if (D.Blogs.COMMENTS.equals(tagName)) {
							mInfo.setComment(parser.nextText());
						} else if (D.Blogs.SOURCENAME.equals(tagName)) {
							mInfo.setAuthor(parser.nextText());
						}
					} else if (eventType == XmlPullParser.END_TAG) {

						String tagName = parser.getName();
						if ("entry".equals(tagName)) {
							mListNews.add(mInfo);
						}
					}
				}

				// //加载listview 布局
				// setAdapter();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return mListNews;
		}

		@Override
		protected void onPostExecute(ArrayList<NewsInfo> result) {
			// TODO Auto-generated method stub

			super.onPostExecute(result);
			if(mpb!=null){
				mpb.setTitle("数据加载完成");
				mpb.dismiss();
			}
			// 加载listview 布局
			//setAdapter();
			if(result.size()>0){
				mAdapter.setData(result);
				//将result赋值给mlistview  防止空指针
				mListNews=result;
			}
		}
	}

	//	/**
	//	 * //判断是否下拉刷新
	//	 */
	//	private void isAbleRefresh() {
	//		mlistview.setOnTouchListener(new OnTouchListener() {
	//
	//			@Override
	//			public boolean onTouch(View v, MotionEvent event) {
	//				switch (event.getAction()) {
	//				case MotionEvent.ACTION_UP:
	//					// TODO Auto-generated method stub
	//					//判断最后一个可见的listview的位置
	//					int position = mlistview.getFirstVisiblePosition();
	//					//得到数组的长度
	////					int size=mListNews.size()-1;
	//					if(position==0){
	//						pullParserNews(uri);
	//					}
	//					break;
	//
	//				default:
	//					break;
	//				}
	//				return false;
	//			}
	//		});
	//		//		// TODO Auto-generated method stub
	//		//		//判断最后一个可见的listview的位置
	//		//		int position = mlistview.getLastVisiblePosition();
	//		//		//得到数组的长度
	//		//		int size=mListnews.size()-1;
	//		//		if(position==size){
	//		//			//如果两个值相等 则说明下拉到最后一行了，则进行刷新
	//		//			Toast.makeText(mContext, "hellp", 2000).show();
	//		//		}
	//	}
}
